
<template>
  <div class="container">
    <h3 class="h3">绘制带有箭头的线</h3>
    <div id="vue-openlayers" />
  </div>
</template>

<script>
import 'ol/ol.css'
import { Map, View } from 'ol'
import Tile from 'ol/layer/Tile'
// import OSM from 'ol/source/OSM'
import LayerVector from 'ol/layer/Vector'
import SourceVector from 'ol/source/Vector'
import Draw from 'ol/interaction/Draw'
import Point from 'ol/geom/Point'
// import Fill from 'ol/style/Fill'
import Stroke from 'ol/style/Stroke'
import Style from 'ol/style/Style'
import Icon from 'ol/style/Icon'
// import { get } from 'ol/proj'
import { XYZ } from 'ol/source'
export default {
  data() {
    return {
      map: null, // 地图
      draw: null,
      source: new SourceVector({
        wrapX: false
      })
    }
  },
  mounted() {
    this.initMap()
  },
  methods: {

    styleFunction(feature) {
      const geometry = feature.getGeometry()
      const styles = [
        new Style({
          stroke: new Stroke({
            color: 'black',
            width: 2
          })
        })
      ]

      geometry.forEachSegment(function(start, end) {
        const dx = end[0] - start[0]
        const dy = end[1] - start[1]
        const rotation = Math.atan2(dy, dx)
        // arrow
        styles.push(
          new Style({
            geometry: new Point(end),
            image: new Icon({
              src: require('@/assets/img/arrow-right.png'),
              anchor: [0.75, 0.5],
              rotateWithView: true,
              rotation: -rotation
            })
          })
        )
      })
      return styles
    },

    addInteraction() {
      if (this.draw !== null) {
        this.map.removeInteraction(this.draw)
      }

      this.draw = new Draw({
        source: this.source,
        type: 'LineString'
      })
      this.map.addInteraction(this.draw)
    },

    initMap() {
      const raster = new Tile({
        source: new XYZ({
          url: 'http://{a-c}.tile.openstreetmap.de/{z}/{x}/{y}.png'
        })
      })

      const vector = new LayerVector({
        source: this.source,
        style: this.styleFunction
      })
      this.map = new Map({
        target: 'vue-openlayers',
        layers: [raster, vector],
        view: new View({
          projection: 'EPSG:4326',
          center: [113.1206, 23.034996],
          zoom: 10
        })
      })
      this.addInteraction()
    }

  }
}
</script>
<style scoped>
.container {
  width: 1240px;
  height: 690px;
  margin: 50px auto;
  border: 1px solid #42b983;
}
#vue-openlayers {
  width: 1200px;
  height: 600px;
  margin: 0 auto;
  margin-top: 10px;
  border: 1px solid #42b983;
  position: relative;
}
.h3 {
  text-align: center;
}
</style>
